#include <Engine.h>
#include <Editor.h>
#include <Context.h>

void Context::Init( char *mapname )
{
	for( int i = 0; i < NB_BLOCS_WIDTH; i++ )
		for( int j = 0; j < NB_BLOCS_HEIGHT; j++)
			map[i][j] = VOID;

	mapName = mapname;

	SaveMap( mapName );

	ActualObject = WALL;
}

void Context::Render( SDL_Surface *surf )
{
	SDL_Rect pos;

	pos.x = 0;
	pos.y = 0;

	for( int i = 0; i < NB_BLOCS_WIDTH; i++ )
	{
		pos.x = BLOC_SIZE * i;

		for( int j = 0; j < NB_BLOCS_HEIGHT; j++ )
		{
			pos.y = BLOC_SIZE * j;

			switch( map[i][j] )
			{
				case VOID:
						Objects[VOID]->SetPos( pos.x, pos.y );
						Objects[VOID]->Blit( surf );
					break;
				case WALL:
						Objects[WALL]->SetPos( pos.x, pos.y );
						Objects[WALL]->Blit( surf );
					break;
				case OBJECTIF:
						Objects[OBJECTIF]->SetPos( pos.x, pos.y );
						Objects[OBJECTIF]->Blit( surf );
					break;
				case CRATE:
						Objects[CRATE]->SetPos( pos.x, pos.y );
						Objects[CRATE]->Blit( surf );
					break;
				case PLAYER:
						Objects[PLAYER]->SetPos( pos.x, pos.y );
						Objects[PLAYER]->Blit( surf );
					break;
			}
		}
	}
}

void Context::SaveMap( char *file )
{
	ofstream map;

	if( file )
	{
		map.open( file, ios::out | ios::trunc | ios::binary );

		if( map )
		{
			for( int i = 0; i < NB_BLOCS_WIDTH; i++ )
				for( int j = 0; j < NB_BLOCS_HEIGHT; j++)
					map.write( (char*)&this->map[i][j], sizeof(int) );

			cout << "Map saved : " << file << endl;

			map.close();
		}
	}
}

void Context::LoadMap(char *file)
{
	ifstream map;

	cout << "Load map : " << file << endl;

	if( file )
	{
		map.open( file, ios::in | ios::binary );

		if( map )
		{
			for( int i = 0; i < NB_BLOCS_WIDTH; i++ )
				for( int j = 0; j < NB_BLOCS_HEIGHT; j++)
					map.read( (char*)&this->map[i][j], sizeof(int) );

			mapName = file;

			map.close();
		}
	}
}

void Context::LoadEvent( Input *in )
{
	switch( in->LastMouseEvent() )
	{
		case LEFT_CLICK:
				map[in->MouseX() / BLOC_SIZE][in->MouseY() / BLOC_SIZE] = ActualObject;
			break;
		case RIGHT_CLICK:
				map[in->MouseX() / BLOC_SIZE][in->MouseY() / BLOC_SIZE] = VOID;
			break;
	}

	switch( in->LastKeyEvent() )
	{
		case SDLK_KP1:
				ActualObject = WALL;
			break;
		case SDLK_KP2:
				ActualObject = OBJECTIF;
			break;
		case SDLK_KP3:
				ActualObject = CRATE;
			break;
		case SDLK_KP4:
				ActualObject = PLAYER;
			break;
		case SDLK_s:
				SaveMap( mapName );
			break;
		case SDLK_c:
				Full( VOID );
			break;
		case SDLK_f:
				Full( WALL );
			break;
		case SDLK_r:
				LoadMap( mapName );
			break;
	}
}

void Context::Full(int Obj)
{
	for( int i = 0; i < NB_BLOCS_WIDTH; i++ )
		for( int j = 0; j < NB_BLOCS_HEIGHT; j++)
			map[i][j] = Obj;

	cout << "Map filled with " << Obj << " object" << endl;
}